<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商店进销存管理系统 - 认证</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .card-shadow {
                @apply shadow-md hover:shadow-xl transition-all duration-300;
            }
            .btn-hover {
                @apply transform hover:scale-[1.02] active:scale-[0.98] transition-transform duration-200;
            }
            .input-focus {
                @apply focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary;
            }
        }
    </style>
</head>
<body class="font-inter bg-gradient-to-br from-blue-50 to-indigo-50 min-h-screen flex items-center justify-center p-4">
<div class="bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden">
    <!-- 顶部品牌区域 -->
    <div class="bg-primary p-6 text-center">
        <i class="fa fa-cubes text-white text-4xl mb-2"></i>
        <h2 class="text-white text-2xl font-bold">商店进销存管理系统</h2>
    </div>

    <!-- 表单区域 -->
    <div class="p-6">
        <div class="flex justify-between items-center mb-6">
            <h3 class="text-2xl font-bold text-gray-800" id="formTitle">登录</h3>
            <div class="flex space-x-2">
                <button id="loginTab" class="px-4 py-2 font-medium text-primary border-b-2 border-primary">登录</button>
                <button id="registerTab" class="px-4 py-2 font-medium text-gray-500 border-b-2 border-transparent">注册</button>
            </div>
        </div>

        <!-- 登录表单 -->
        <div id="loginFormContainer">
            <form id="loginForm">
                <div class="mb-4">
                    <label for="loginUsername" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
                            <i class="fa fa-user"></i>
                        </span>
                        <input type="text" id="loginUsername" class="w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg input-focus" placeholder="请输入用户名">
                    </div>
                </div>
                <div class="mb-6">
                    <label for="loginPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
                            <i class="fa fa-lock"></i>
                        </span>
                        <input type="password" id="loginPassword" class="w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg input-focus" placeholder="请输入密码">
                    </div>
                </div>
                <button type="submit" class="w-full py-3 px-4 bg-primary text-white rounded-lg btn-hover shadow-md hover:shadow-lg">
                    <i class="fa fa-sign-in mr-2"></i>登录
                </button>
            </form>
        </div>

        <!-- 注册表单 -->
        <div id="registerFormContainer" class="hidden">
            <form id="registerForm">
                <div class="mb-4">
                    <label for="registerUsername" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
                            <i class="fa fa-user-plus"></i>
                        </span>
                        <input type="text" id="registerUsername" class="w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg input-focus" placeholder="请设置用户名">
                    </div>
                </div>
                <div class="mb-4">
                    <label for="registerPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
                            <i class="fa fa-lock"></i>
                        </span>
                        <input type="password" id="registerPassword" class="w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg input-focus" placeholder="请设置密码">
                    </div>
                </div>
                <div class="mb-4">
                    <label for="registerConfirmPassword" class="block text-sm font-medium text-gray-700 mb-1">确认密码</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
                            <i class="fa fa-lock"></i>
                        </span>
                        <input type="password" id="registerConfirmPassword" class="w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg input-focus" placeholder="请再次输入密码">
                    </div>
                </div>
                <div class="mb-6">
                    <label for="salesmanId" class="block text-sm font-medium text-gray-700 mb-1">业务员编号</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
                            <i class="fa fa-id-card"></i>
                        </span>
                        <input type="text" id="salesmanId" class="w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg input-focus" placeholder="请输入业务员编号">
                    </div>
                </div>
                <button type="submit" class="w-full py-3 px-4 bg-primary text-white rounded-lg btn-hover shadow-md hover:shadow-lg">
                    <i class="fa fa-user-plus mr-2"></i>注册
                </button>
            </form>
        </div>
    </div>
</div>

<script>
    // 获取DOM元素
    const loginTab = document.getElementById('loginTab');
    const registerTab = document.getElementById('registerTab');
    const loginFormContainer = document.getElementById('loginFormContainer');
    const registerFormContainer = document.getElementById('registerFormContainer');
    const formTitle = document.getElementById('formTitle');
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');

    // 切换到登录表单
    loginTab.addEventListener('click', () => {
        loginFormContainer.classList.remove('hidden');
        registerFormContainer.classList.add('hidden');
        loginTab.classList.add('text-primary', 'border-primary');
        loginTab.classList.remove('text-gray-500', 'border-transparent');
        registerTab.classList.add('text-gray-500', 'border-transparent');
        registerTab.classList.remove('text-primary', 'border-primary');
        formTitle.textContent = '登录';
    });

    // 切换到注册表单
    registerTab.addEventListener('click', () => {
        loginFormContainer.classList.add('hidden');
        registerFormContainer.classList.remove('hidden');
        loginTab.classList.remove('text-primary', 'border-primary');
        loginTab.classList.add('text-gray-500', 'border-transparent');
        registerTab.classList.remove('text-gray-500', 'border-transparent');
        registerTab.classList.add('text-primary', 'border-primary');
        formTitle.textContent = '注册';
    });

    // 登录表单提交处理
    loginForm.addEventListener('submit', async function(e) {
        e.preventDefault();

        const username = document.getElementById('loginUsername').value;
        const password = document.getElementById('loginPassword').value;

        if (!username || !password) {
            showNotification('请输入用户名和密码', 'error');
            return;
        }

        try {
            showLoading(true);
            const response = await fetch('/login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`
            });

            if (response.ok) {
                // 假设后端返回"ok"状态
                showNotification('登录成功！正在跳转...', 'success');
                setTimeout(() => {
                    window.location.href = '/index.html'; // 固定跳转地址
                }, 1500);
            } else {
                showNotification('登录失败：用户名或密码错误', 'error');
            }
        } catch (error) {
            showNotification('登录请求失败：' + error.message, 'error');
        } finally {
            showLoading(false);
        }
    });

    // 注册表单提交处理
    registerForm.addEventListener('submit', async function(e) {
        e.preventDefault();

        const username = document.getElementById('registerUsername').value;
        const password = document.getElementById('registerPassword').value;
        const confirmPassword = document.getElementById('registerConfirmPassword').value;
        const salesmanId = document.getElementById('salesmanId').value;

        // 简单表单验证
        if (!username || !password || !salesmanId) {
            showNotification('请填写所有必填字段', 'error');
            return;
        }

        if (password !== confirmPassword) {
            showNotification('两次输入的密码不一致', 'error');
            return;
        }

        try {
            showLoading(true);

            // 构造包含roles字段的注册数据
            const registerData = {
                username: username,
                password: password,
                roles: ["USER"] // 包含默认角色USER，无ROLE_前缀
            };

            const response = await fetch(`/register/${salesmanId}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }, // 使用JSON格式
                body: JSON.stringify(registerData) // 将数据转换为JSON字符串
            });

            if (response.ok) {
                // 假设后端返回"ok"状态
                showNotification('注册成功！请登录', 'success');
                setTimeout(() => {
                    loginTab.click(); // 切换到登录表单
                }, 1500);
            } else {
                // 尝试解析错误信息
                let errorMessage = '注册失败';
                try {
                    const errorData = await response.json();
                    if (errorData.message) {
                        errorMessage += ': ' + errorData.message;
                    }
                } catch {
                    errorMessage += ': 用户名可能已存在';
                }
                showNotification(errorMessage, 'error');
            }
        } catch (error) {
            showNotification('注册请求失败：' + error.message, 'error');
        } finally {
            showLoading(false);
        }
    });

    // 显示通知
    function showNotification(message, type = 'info') {
        // 移除现有通知
        const existingNotification = document.querySelector('.notification');
        if (existingNotification) {
            existingNotification.remove();
        }

        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 ease-in-out translate-y-[-20px] opacity-0`;

        // 设置通知类型样式
        if (type === 'success') {
            notification.classList.add('bg-green-50', 'border-l-4', 'border-green-400', 'text-green-700');
            notification.innerHTML = `
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <i class="fa fa-check-circle text-green-500"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium">${message}</p>
                    </div>
                </div>
            `;
        } else if (type === 'error') {
            notification.classList.add('bg-red-50', 'border-l-4', 'border-red-400', 'text-red-700');
            notification.innerHTML = `
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <i class="fa fa-exclamation-circle text-red-500"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium">${message}</p>
                    </div>
                </div>
            `;
        } else {
            notification.classList.add('bg-blue-50', 'border-l-4', 'border-blue-400', 'text-blue-700');
            notification.innerHTML = `
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <i class="fa fa-info-circle text-blue-500"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium">${message}</p>
                    </div>
                </div>
            `;
        }

        // 添加到文档
        document.body.appendChild(notification);

        // 显示动画
        setTimeout(() => {
            notification.classList.remove('translate-y-[-20px]', 'opacity-0');
        }, 10);

        // 自动关闭
        setTimeout(() => {
            notification.classList.add('translate-y-[-20px]', 'opacity-0');
            setTimeout(() => notification.remove(), 300);
        }, 4000);
    }

    // 显示/隐藏加载状态
    function showLoading(isLoading) {
        const loginButton = loginForm.querySelector('button[type="submit"]');
        const registerButton = registerForm.querySelector('button[type="submit"]');

        if (isLoading) {
            loginButton.disabled = true;
            registerButton.disabled = true;

            loginButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>登录中...';
            registerButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>注册中...';
        } else {
            loginButton.disabled = false;
            registerButton.disabled = false;

            loginButton.innerHTML = '<i class="fa fa-sign-in mr-2"></i>登录';
            registerButton.innerHTML = '<i class="fa fa-user-plus mr-2"></i>注册';
        }
    }
</script>
</body>
</html>